# -*- coding: utf-8 -*-
"""
Module Description:
Date: 2018/12/12
Author: FQ
"""
from pyshare.dal.repository_impl import DistributedTransactionStatRepository
from pyshare.core.context import get_trace_id

from functools import wraps

from pyshare.utils.service_switch import is_open_dts
from pyshare.framework.error_handle import CrossGameException
from pyshare.utils.json_utils import dumps


def record_cross_stat(func):
    """
    记录接口执行状态
    """

    @wraps(func)
    def wrapper(*args, **kwargs):

        if is_open_dts():
            trace_id = get_trace_id()
            DistributedTransactionStatRepository.update_cross_start(trace_id)
            try:
                return_date = func(*args, **kwargs)
            except CrossGameException as e:
                # 捕获游戏异常状态
                return_date = e.as_dict({'Stat': e.stat, 'Info': e.message})
            try:
                res = dumps(return_date)
            except:
                res = "{}"
            DistributedTransactionStatRepository.update_cross_complete(trace_id, res)
            return return_date
        else:
            return func(*args, **kwargs)

    return wrapper